package com.cc.cbdb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.widget.TextView;

import com.cc.cbdb.R;
import com.cc.cbdb.view.LoadingDialog;
import com.cc.cbdb.view.x5WebView.Android2Js;
import com.cc.cbdb.view.x5WebView.MyWebChromeClient;
import com.cc.cbdb.view.x5WebView.X5WebView;
import com.tencent.smtt.sdk.WebView;

public class X5WebViewActivity extends AppCompatActivity{

    private X5WebView mX5WebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_x5_web_view);
        initHardwareAccelerate();
        initView();
    }

    private void initView(){
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");
        String title = intent.getStringExtra("title");

        LoadingDialog.Builder builder = new LoadingDialog.Builder(this);
        builder.setMessage("加载中...");
        final LoadingDialog loadingDialog = builder.create();
        loadingDialog.show();
        mX5WebView = findViewById(R.id.x5_webview);
        mX5WebView.setWebChromeClient(new MyWebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    loadingDialog.dismiss();
                }
            }
        });
        mX5WebView.addJavascriptInterface(new Android2Js(X5WebViewActivity.this),"androidFunc");
        TextView tv_title = findViewById(R.id.titleBar);

        tv_title.setText(title);
        mX5WebView.loadUrl(url);
    }

    /**
     * 启用硬件加速
     */
    private void initHardwareAccelerate() {
        try {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 11) {
                getWindow()
                        .setFlags(
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                                android.view.WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回键监听
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mX5WebView != null && mX5WebView.canGoBack()) {
                mX5WebView.goBack();
                return true;
            } else {
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        //释放资源
        if (mX5WebView != null)
            mX5WebView.destroy();
        super.onDestroy();
    }

}
